<?php

namespace App\Http\Controllers\Admin;


use App\Models\Live;
use App\Models\LiveChannel;
use Illuminate\Http\Request;

class LiveController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get(Request $request)
    {
        $live = Live::findOrFail($request->input('id'));
        return ajaxReturn(['live' => $live]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchget(Request $request)
    {
        $items = Live::with(['channel', 'user'])->offset($request->input('offset', 0))
            ->limit($request->input('count', 15))->orderByDesc('id')
            ->get([
                'id', 'uid', 'channel_id', 'stream_id', 'title',
                'image', 'state', 'views', 'start_at', 'expires_at', 'created_at', 'updated_at'
            ]);
        return ajaxReturn(['items' => $items]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function save(Request $request)
    {
        $live = Live::findOrNew($request->input('id'));
        $live->fill($request->input('live', []))->save();
        return ajaxReturn(['live' => $live]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        Live::whereKey($request->input('items', []))->get()->map(function (Live $live) {
            $live->delete();
        });

        return ajaxReturn();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchgetChannel(Request $request)
    {
        $items = LiveChannel::all();
        return ajaxReturn(['items' => $items]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveChannel(Request $request)
    {
        $channel = LiveChannel::findOrNew($request->input('channel_id'));
        $channel->fill($request->input('channel', []))->save();
        return ajaxReturn(['channel' => $channel]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteChannel(Request $request)
    {
        LiveChannel::whereKey($request->input('items', []))->get()->map(function (LiveChannel $liveChannel) {
            $liveChannel->delete();
        });

        return ajaxReturn();
    }
}
